<template>
  <div class="add-role-container">
    <div class="title-content">
      <div class="title">{{ title }}</div>
      <div class="check-grounp">
        <a-checkbox v-if="treeData.length !== 0" class="check-item mr" v-model="isExpand" @change="changeExpand">展开</a-checkbox>
        <a-checkbox v-if="!disabled" class="check-item" v-model="isChangeAll" @change="changeAll">全选</a-checkbox>
      </div>
    </div>
    <div class="tree-content">
      <a-empty v-if="treeData.length == 0" />
      <a-tree
        :checkable="!disabled"
        v-model:checked-keys="checkedKeys"
        v-model:expanded-keys="expandedKeys"
        v-model:half-checked-keys="halfCheckedKeys"
        @check="onCheck"
        @expand="onExpand"
        :data="treeData"
      >
        <template #extra="nodeData">
          <span class="type-text">{{ nodeData.type }}</span>
        </template>
      </a-tree>
    </div>
  </div>
</template>

<script setup>
  import { getResource } from '@/api/merchant/role'
  import { useRoute } from 'vue-router'
  import { ref, onMounted, watch } from 'vue'

  const props = defineProps({
    title: String,
    index: {
      type: Number,
      default: 0,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    id: String,
  })
  const emit = defineEmits(['checkChange'])

  watch(
    () => props.id,
    (val) => {
      if (val) {
        getRoleList(val)
      }
    }
  )
  // 全选key
  const allCheckedKeys = ref([])
  // 全部展开key
  const allExpandedKeys = ref([])

  const checkedKeys = ref([])
  const expandedKeys = ref([])
  const halfCheckedKeys = ref([])

  const treeData = ref([])
  const isExpand = ref(false)
  // 全选
  const isChangeAll = ref(false)

  const queryParams = ref({
    id: useRoute().params.id || null,
  })
  // 树状选择器列表数据处理
  const transformTree = (val) => {
    const list = []
    let propDisabled = props.disabled
    val.forEach((i) => {
      const treeItem = {
        key: i.id,
        title: i.name,
        type: i.type,
        hasRole: i.hasRole,
      }
      if (i.children && i.children.length > 0) {
        treeItem.children = transformTree(i.children)
      }
      if (!propDisabled || (propDisabled && i.hasRole)) {
        list.push(treeItem)
      }
    })
    return list
  }

  // 全部选中节点数据处理
  const setAllVal = (list, arr) => {
    list.forEach((v) => {
      arr.push(v.key)
      if (v.children) {
        setAllVal(v.children, arr)
      }
    })
    return arr
  }
  // 全部展开节点数据处理
  const setChildrenVal = (list, arr) => {
    list.forEach((v) => {
      if (v.children) {
        arr.push(v.key)
        setChildrenVal(v.children, arr)
      }
    })
    return arr
  }
  // 选中节点数据处理
  const setCheckedVal = (list, checkedKeys, halfCheckedKeys) => {
    list.forEach((v) => {
      if (v.hasRole) {
        if (v.children) {
          halfCheckedKeys.push(v.key)
        } else {
          checkedKeys.push(v.key)
        }
      }
      if (v.children) {
        setCheckedVal(v.children, checkedKeys, halfCheckedKeys)
      }
    })
  }
  // 树形选择框列表
  const getRoleList = (val) => {
    queryParams.value.id = val // ? val : queryParams.value.id
    getResource(queryParams.value).then((res) => {
      const roleData = transformTree(res.result[props.index].children)
      treeData.value = roleData
      let _checkedKeys = []
      let _halfCheckedKeys = []
      setCheckedVal(roleData, _checkedKeys, _halfCheckedKeys)
      checkedKeys.value = _checkedKeys
      halfCheckedKeys.value = _halfCheckedKeys
      allCheckedKeys.value = setAllVal(roleData, [])
      if (allCheckedKeys.value.length == checkedKeys.value.length + halfCheckedKeys.value.length) {
        isChangeAll.value = true
      }
      allExpandedKeys.value = setChildrenVal(roleData, [])

      // 将checkedKeys 和 halfCheckedKeys 合并传递
      // console.log('checkedKeys', checkedKeys.value)
      // console.log('halfCheckedKeys', halfCheckedKeys.value)
      emit('checkChange', checkedKeys.value.concat(halfCheckedKeys.value))
    })
  }
  // 全部展开
  const changeExpand = (e) => {
    // expandedKeys.value = expandedKeys?.value.length ? [] : allExpandedKeys
    expandedKeys.value = e ? allExpandedKeys.value : []
  }
  // 全部选中
  const changeAll = (e) => {
    checkedKeys.value = e ? allCheckedKeys.value : []

    if (e) {
      emit('checkChange', allCheckedKeys.value)
    } else {
      emit('checkChange', [])
    }
    // checkedKeys.value = checkedKeys?.value.length ? [] : allCheckedKeys
  }
  // 单个选中
  const onCheck = (checkedKeys, data) => {
    const halfCheckedKeys = data.halfCheckedKeys
    if (allCheckedKeys.value.length == checkedKeys.length) {
      isChangeAll.value = true
    } else {
      isChangeAll.value = false
    }
    emit('checkChange', checkedKeys.concat(halfCheckedKeys))
  }
  // 单个展开
  const onExpand = (newExpandedKeys, event) => {
    console.log('expand: ', newExpandedKeys, event)
  }
  defineExpose({
    getRoleList,
  })
  onMounted(() => {
    getRoleList(props.id)
  })
</script>
<style lang="less" scoped>
  .add-role-container {
    width: 100%;

    border: 1px solid #f2f3f5;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    .title-content {
      background: #f2f3f5;
      padding: 12px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      .title {
        font-weight: 600;
        color: #1d2129;
        line-height: 17px;
        font-size: 14px;
      }
      .check-grounp {
        display: flex;
      }
      .mr{
        margin-right: 30px;
      }
    }
    .tree-content {
      padding: 6px;
      height: 500px;
      overflow-y: auto;
    }
    .type-text {
      position: absolute;
      right: 8px;
    }
  }
</style>
